package com.sloan.community.util;

import lombok.extern.slf4j.Slf4j;
import org.jcodec.api.FrameGrab;
import org.jcodec.common.io.FileChannelWrapper;
import org.jcodec.common.model.Picture;
import org.jcodec.scale.AWTUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.time.LocalDate;
import java.util.Objects;

@Slf4j
public class ImageVideoUtils {

    public static String FILE_EXT = "jpg";

    public static String getFileExtension(String filename) {
        int lastDotIndex = filename.lastIndexOf('.');
        if (lastDotIndex == -1) {
            return "";
        }
        // 返回扩展名，不包括点（.）
        return filename.substring(lastDotIndex + 1);
    }

    public static String uploadPath(String mkdir) {
        LocalDate now = LocalDate.now();
        int year = now.getYear();
        int month = now.getMonth().getValue();
        int day = now.getDayOfMonth();
        return mkdir + "/images/" + year + "/" + month + "/" + day + "/";
    }

    public static ByteArrayInputStream getFirstFrame(FileInputStream inputStream, Integer frame) {
        if(Objects.isNull(inputStream)) {
            throw new RuntimeException("数据流出现问题");
        }
        try {
            long startTime = System.currentTimeMillis();
            FileChannelWrapper fileChannelWrapper = new FileChannelWrapper(inputStream.getChannel());
            Picture picture =FrameGrab.getFrameFromChannel(fileChannelWrapper, frame);
            BufferedImage bufferedImage = AWTUtil.toBufferedImage(picture);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, FILE_EXT, baos);
            log.info("视频第一帧截取花费时间:{} ms",(System.currentTimeMillis() - startTime));
            return new ByteArrayInputStream(baos.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
